<?php

namespace App\Http\Controllers\Client\Shop\Goods;

use App\Http\Controllers\ClientController;
use App\Models\Common\File;
use App\Models\Tools\AliOss;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GoodsCreateController extends ClientController
{

    public function index()
    {

        $all = $this->all;
        // 验证参数
        $verify = self::verify();
        if(!$verify){
            return $this->setReturnJson(-1,'参数错误');
        }

        if(isset($all['goods_id'])){
            $result = self::edit();
        } else {
            $result = self::create();
        }
        return $this->setReturnJson(...$result);
    }

    /**
     * 参数验证
     * @return bool
     */
    private function verify()
    {
        $all = $this->all;
        // 验证参数
        try {
            if (!isset($all['goods_name'])) {
                throw new \Exception('缺少参数:goods_name');
            }
            if (!isset($all['shop_id'])) {
                throw new \Exception('缺少参数:shop_id');
            }
            if (!isset($all['price'])) {
                throw new \Exception('缺少参数:price');
            }
            if (!isset($all['detail'])) {
                throw new \Exception('缺少参数:detail');
            }
            if(!isset($all['goods_id'])){ // 新建:必须有title_img和goods_img
                if (!isset($all['title_img'])) {
                    throw new \Exception('缺少参数:title_img');
                }
                if (!isset($all['goods_img'])) {
                    throw new \Exception('缺少参数:goods_img');
                }
            }
        }catch (\Exception $e) {
            Log::error(GoodsCreateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return false;
        }
        return true;
    }

    /**
     * 创建活动策略
     * @return array
     */
    private function create()
    {
        $all = $this->all;
        try {
            DB::beginTransaction();

            $title_img = $all['title_img'];
            $goods_img = $all['goods_img'];

            // 新建商品
            $goods_id = DB::table('lottery_goods')->insertGetId([
                'goods_name' => $all['goods_name'],
                'shop_id' => $all['shop_id'],
                'price' => $all['price'],
                'title_img' => '',
                'goods_img' => '',
                'detail' => $all['detail'],
                'creator'=>$this->we_id,
            ]);

            /**
             * 下载并保存图片
             */
            $file_path = 'images/goods/' . $goods_id;
            // 下载标题图片
            $title_img = File::saveMedia($title_img, $file_path);
            // 下载商品图片
            $images = [];
            foreach ($goods_img as $key => $value) {
                $images[] = File::saveMedia($value, $file_path);
            }
            $goods_img = implode(',', $images);

            DB::table('lottery_goods')->where('goods_id','=',$goods_id)->update([
                'title_img' => $title_img,
                'goods_img' => $goods_img,
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(GoodsCreateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return [-1, '申请失败，请重试或联系人工客服'];
        }
        return [0,'配置完成，请进入订单管理，发布你的霸王餐'];
    }

    /**
     * 编辑活动策略
     * @return array
     */
    private function edit()
    {
        $all = $this->all;
        try{
            // 验证当前用户是否是策略的所有者
            $goods_message = DB::table('lottery_goods')->where('goods_id','=',$all['goods_id'])->first();
            $goods_message = json_decode(json_encode($goods_message), true);
            if($this->we_id !== $goods_message['creator']){
                return [-1,'您不是当前活动策略的所有者'];
            }

            $update_array = [
                'goods_name' => $all['goods_name'],
                'shop_id' => $all['shop_id'],
                'price' => $all['price'],
                'detail' => $all['detail'],
            ];

            // 如果上传了图片
            if(isset($all['title_img']) && $all['title_img']){
                // 下载标题图片
                $update_array['title_img'] = File::saveMedia($all['title_img'], 'images/goods/' . $all['goods_id']);
            }
            if(isset($all['goods_img']) && count($all['goods_img'])){
                // 下载商品图片
                $images = [];
                foreach ($all['goods_img'] as $key => $value) {
                    $images[] = File::saveMedia($value, 'images/goods/' . $all['goods_id']);
                }
                $update_array['goods_img'] = implode(',', $images);
            }
            DB::table('lottery_goods')->where('goods_id','=',$all['goods_id'])->update($update_array);
        } catch (\Exception $e) {
            Log::error(GoodsCreateController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return [-1, '更新失败'];
        }
        return [0,'配置完成，请进入订单管理，发布你的霸王餐'];
    }

}
